package checker

import (
	"context"
	"fmt"
	"net"
	"time"
)

type TCPChecker struct {
	name    string
	host    string
	port    int
	timeout time.Duration
}

func NewTCPChecker(name, host string, port int, timeout time.Duration) *TCPChecker {
	return &TCPChecker{
		name:    name,
		host:    host,
		port:    port,
		timeout: timeout,
	}
}

func (c *TCPChecker) Name() string {
	return c.name
}

func (c *TCPChecker) Check(ctx context.Context) Result {
	addr := fmt.Sprintf("%s:%d", c.host, c.port)
	dialer := &net.Dialer{}
	ctx, cancel := context.WithTimeout(ctx, c.timeout)
	defer cancel()

	conn, err := dialer.DialContext(ctx, "tcp", addr)
	if err != nil {
		return Result{
			Name:   c.name,
			OK:     false,
			Error:  err,
			Detail: fmt.Sprintf("dial %s failed", addr),
		}
	}
	conn.Close()
	return Result{
		Name:   c.name,
		OK:     true,
		Detail: fmt.Sprintf("tcp %s connected", addr),
	}
}
